package com.yunze.system.card;

import com.alibaba.fastjson.JSON;
import com.yunze.common.core.redis.RedisCache;
import com.yunze.common.mapper.mysql.YzExecutionTaskMapper;
import com.yunze.common.mapper.mysql.warehouse.Administration.YzCkglInventorydetailsMapper;
import com.yunze.common.utils.yunze.WriteCSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/*
 * 明细表 卡划分
 */
@Slf4j
@Component
public class DetailedDivision {

    @Resource
    private RedisCache redisCache;
    @Resource
    private DistributeCard distributeCard;
    @Resource
    private YzExecutionTaskMapper yzExecutionTaskMapper;
    @Resource
    private YzCkglInventorydetailsMapper yzCkglInventorydetailsMapper;
    @Resource
    private WriteCSV writeCSV;

    /**
     * 卡划分
     *
     * @param msg
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = "admin_DivideInventorydetails_queue")
    public void DbCard(String msg) throws IOException {
        try {
            if (StringUtils.isEmpty(msg)) {
                return;
            }
            Map<String, Object> map = JSON.parseObject(msg);
            List<Map<String, Object>> listInv = (List<Map<String, Object>>) map.get("listInv");
            Map<String, Object> User = (Map<String, Object>) map.get("User");//登录用户信息
            String prefix = "admin_DivideInventorydetails_queue";
            //执行前判断 redis 是否存在 执行数据 存在时 不执行
            String set_dept_name = map.get("set_dept_name").toString();//上传新文件名

            Object isExecute = redisCache.getCacheObject(prefix + ":" + set_dept_name);
            if (isExecute == null) {
                redisCache.setCacheObject(prefix + ":" + set_dept_name, msg, 10, TimeUnit.SECONDS);//10 秒缓存 避免 重复消费
                execution(map, listInv,User);//执行卡划分
            }
        } catch (Exception e) {
            log.error(">>错误 - 卡划分 消费者:{}<<", e.getMessage().toString());
        }
    }

    private void execution(Map<String, Object> map, List<Map<String, Object>> listInv,Map<String, Object> User) {

        String Message = "";

        //1.备份现有卡所属信息
        String set_dept_name = map.get("set_dept_name").toString();
        String set_user_name = map.get("set_user_name").toString();
        String create_by = " [ " + set_dept_name + " ] - " + " [ " + set_user_name + " ] ";
        String newName = UUID.randomUUID().toString().replace("-", "") + "_CardDetailed";
        String Name = UUID.randomUUID().toString().replace("-","")+"_Detailed";
        String  agent_id = map.get("TaskAgent_id").toString();
        String task_name = "库存明细 [划卡] ";
        String SaveUrl = "/getcsv/" + newName + ".csv";
        SaveUrl += ",/getcsv/"+Name+".csv";
        Map<String, Object> task_map = new HashMap<String, Object>();
        task_map.put("auth", create_by);
        task_map.put("task_name", task_name);
        task_map.put("url", SaveUrl);
        task_map.put("agent_id", agent_id);
        task_map.put("type", "33");//任务类别

        yzExecutionTaskMapper.add(task_map);//添加执行 任务表

        distributeCard.OutCSV(listInv,Name,create_by);

        List<Map<String,Object>> listId = yzCkglInventorydetailsMapper.BackupId(map);
        List<String> StrList = new ArrayList<>();
        //遍历List<Map<String,Object>> 放到 List<String>
        for (Map<String, Object> mapOpj : listId) {
            for (String s : mapOpj.keySet()) {
                System.out.println(s);
                StrList.add(mapOpj.get(s) + " ");
            }
        }
        //2.开始划卡
        Map<String, Object> newPmap = new HashMap<>();
        newPmap.put("set_dept_id", map.get("set_dept_id"));
        newPmap.put("set_user_id", map.get("set_user_id"));
        newPmap.put("idArr", StrList);

        Integer updCount = yzCkglInventorydetailsMapper.updateDivid(newPmap);
        if (updCount > 0) {
            Message = "当前筛选条件下需要划分的数据 [ " + StrList.size() + " ] 条，成功划分 [ " + updCount + " ] 条，至 [ " + set_dept_name + " ] [ " + set_user_name + " ] ！";
            log.info(Message);
        } else {
            Message = "当前筛选条件下需要划分的数据 [ " + StrList.size() + " ] 条 至 [ " + set_dept_name + " ] [ " + set_user_name + " ] 划分失败 ！";
            log.error(Message);
        }
        distributeCard.OutCSVUpd(StrList, set_dept_name, set_user_name, newName, create_by, Message);

        yzExecutionTaskMapper.set_end_time(task_map);
    }

}
